// pages/exam/exam.js
Page({
  data: {
    currentQuestionIndex: 0,
    questions: [],
    remainingTime: 0,
    timeText: '',
    timerWidth: '100%',
    isTimeUp: false,
    userAnswers: {}
  },
  onLoad: function() {
    const app = getApp();
    if (!app.globalData.isExamStarted || !app.globalData.examQuestions) {
      wx.navigateBack();
      return;
    }

    this.setData({
      questions: app.globalData.examQuestions
    });

    // 初始化计时器
    this.initTimer();
  },
  initTimer: function() {
    const app = getApp();
    const duration = app.globalData.duration;
    const startTime = app.globalData.startTime;

    this.updateTimer(startTime, duration);

    // 每秒更新一次计时器
    this.timer = setInterval(() => {
      this.updateTimer(startTime, duration);
    }, 1000);
  },
  updateTimer: function(startTime, duration) {
    const now = Date.now();
    const elapsed = now - startTime;
    const remaining = duration - elapsed;

    if (remaining <= 0) {
      this.setData({
        remainingTime: 0,
        timeText: '00:00',
        timerWidth: '0%',
        isTimeUp: true
      });
      clearInterval(this.timer);
      this.submitExam();
      return;
    }

    const minutes = Math.floor(remaining / 60000);
    const seconds = Math.floor((remaining % 60000) / 1000);
    const timeText = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    const timerWidth = `${(remaining / duration) * 100}%`;

    this.setData({
      remainingTime: remaining,
      timeText: timeText,
      timerWidth: timerWidth
    });
  },
  selectOption: function(e) {
    if (this.data.isTimeUp) return;

    const questionIndex = e.currentTarget.dataset.questionIndex;
    const option = e.currentTarget.dataset.option;
    const question = this.data.questions[questionIndex];
    const questionId = question.id;

    // 获取页面本地的userAnswers和全局的userAnswers
    const app = getApp();
    const globalUserAnswers = app.globalData.userAnswers;
    const localUserAnswers = { ...this.data.userAnswers };

    // 判断是否为多选题（id >= 100的是多选题）
    const isMultiple = questionId >= 100;

    // 更新本地和全局的答案
    if (!isMultiple) {
      // 单选题
      localUserAnswers[questionId] = option;
      globalUserAnswers[questionId] = option;
    } else {
      // 多选题
      // 初始化数组（如果不存在）
      if (!localUserAnswers[questionId]) {
        localUserAnswers[questionId] = [];
      }
      if (!globalUserAnswers[questionId]) {
        globalUserAnswers[questionId] = [];
      }

      // 处理本地答案
      const localIndex = localUserAnswers[questionId].indexOf(option);
      if (localIndex > -1) {
        // 取消选择
        localUserAnswers[questionId].splice(localIndex, 1);
      } else {
        // 添加选择
        localUserAnswers[questionId].push(option);
      }

      // 同步到全局答案
      const globalIndex = globalUserAnswers[questionId].indexOf(option);
      if (globalIndex > -1) {
        // 取消选择
        globalUserAnswers[questionId].splice(globalIndex, 1);
      } else {
        // 添加选择
        globalUserAnswers[questionId].push(option);
      }
    }

    // 更新页面数据，触发视图重新渲染
    console.log('Updating userAnswers:', localUserAnswers);
    this.setData({
      userAnswers: localUserAnswers
    });
  },
  isOptionSelected: function(questionId, option) {
    // 从页面data中获取userAnswers
    const userAnswers = this.data.userAnswers || {};
    console.log('Checking option selected:', questionId, option, userAnswers);

    // 确保questionId存在于userAnswers中
    if (!userAnswers.hasOwnProperty(questionId)) {
      return false;
    }

    // 判断是否为多选题（id >= 100的是多选题）
    const isMultiple = questionId >= 100;

    // 确保option类型与userAnswers中存储的类型匹配
    option = String(option);

    // 单选题
    if (!isMultiple) {
      return String(userAnswers[questionId]) === option;
    }
    // 多选题
    // 确保userAnswers[questionId]是数组
    if (!Array.isArray(userAnswers[questionId])) {
      return false;
    }
    return userAnswers[questionId].map(String).includes(option);
  },
  prevQuestion: function() {
    if (this.data.currentQuestionIndex > 0) {
      this.setData({
        currentQuestionIndex: this.data.currentQuestionIndex - 1
      });
    }
  },
  nextQuestion: function() {
    if (this.data.currentQuestionIndex < this.data.questions.length - 1) {
      this.setData({
        currentQuestionIndex: this.data.currentQuestionIndex + 1
      });
    }
  },
  submitExam: function() {
    if (this.data.isTimeUp) {
      wx.showToast({
        title: '考试时间已结束，自动提交',
        icon: 'none'
      });
    }

    clearInterval(this.timer);
    wx.navigateTo({
      url: '/pages/result/result'
    });
  },
  onUnload: function() {
    // 清除计时器
    clearInterval(this.timer);
  }
})